package com.boot.cluster.worker.selector;

import com.boot.cluster.worker.bean.Node;
import com.boot.cluster.worker.bean.TaskSplitterInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 任务hash分配器
 *
 * @author lichunwen
 */
public class HashSelector implements Selector<Node, TaskSplitterInfo> {

    private static Logger logger = LoggerFactory.getLogger(HashSelector.class);

    @Override
    public String name() {
        return null;
    }

    @Override
    public Map<Node, List<TaskSplitterInfo>> selector(List<Node> t, List<TaskSplitterInfo> e) {
        if ((t == null) || t.isEmpty() || (e == null) || e.isEmpty()) {
            logger.warn("Cluster state anomaly");
            return new HashMap<>();
        }
        Map<Node, List<TaskSplitterInfo>> m = new HashMap<>();
        t.forEach(s -> m.put(s, new ArrayList<>()));
        int size = t.size();
        e.forEach(s -> {
            int index = Math.abs(s.hashCode() % size);
            m.get(t.get(index)).add(s);
        });
        return m;
    }

}
